<template>
  <div class="login flex-center">
    <div class="window text-align-center flex-column flex-center ">
       <header class="l-h-60 m-b-20 flex-column fz-18 w-350">
         <span class="cursor-pointer p-b-5 p-l-5 p-r-5" :class="{active: isLogin}" @click="isLogin = true">登录</span>
         <strong class="m-r-10 m-l-10 fz-25"> · </strong>
         <span class="cursor-pointer p-b-5 p-l-5 p-r-5" :class="{active: !isLogin}" @click="isLogin = false">注册</span> 
       </header>
      <!-- 登录开始 -->
      <transition name="fade" mode="out-in">
        <div v-show="isLogin" class="w-300 h-280">
          <el-form :model="loginForm" status-icon :rules="loginRules" ref="loginForm" label-width="auto">
            <el-form-item prop="username">
              <el-input prefix-icon="el-icon-user" placeholder="请输入昵称" type="text" minlength="1" maxlength="10" v-model="loginForm.username"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input prefix-icon="el-icon-s-grid" placeholder="请输入密码" type="password" v-model="loginForm.password" autocomplete="off"></el-input>
            </el-form-item>
            <div class="m-b-10 flex flex-space-between">
              <el-checkbox v-model="isSaveLoginState">保存状态</el-checkbox>
            </div>
            <div>
              <el-button type="primary" class="W100 m-b-10 box-shadow-hover" :loading="login" @click="loginSubmit('loginForm')" round>登录</el-button>
            </div>
            <el-button type="text" @click="resetForm('loginForm')" round>重置</el-button>
          </el-form>
        </div>
      </transition>
      <!-- 登录结束 -->
      
      <!-- 注册开始 -->
      <transition name="fade" mode="out-in">
        <div v-show="!isLogin" class="w-300 h-280">
          <el-form :model="registerFrom" status-icon :rules="registerRules" ref="registerFrom" label-width="auto">
            <el-form-item prop="registerUsername">
              <el-input prefix-icon="el-icon-user" placeholder="请输入昵称" minlength="1" maxlength="10" v-model="registerFrom.registerUsername"></el-input>
            </el-form-item>
            <el-form-item prop="registerKey">
              <el-input prefix-icon="el-icon-tickets" placeholder="请输入密钥" v-model="registerFrom.registerKey" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop="registerPassword">
              <el-input prefix-icon="el-icon-s-grid" placeholder="请输入密码" type="password" v-model="registerFrom.registerPassword" autocomplete="off"></el-input>
            </el-form-item>
            <div>
              <el-button type="primary" class="W100 m-b-10 box-shadow-hover" :loading="register" @click="registerSubmit('registerFrom')" round>注册</el-button>
            </div>
            <el-button type="text" @click="resetForm('registerFrom')" round>重置</el-button>
          </el-form>
        </div>  
      </transition>
      <!-- 注册结束 -->

    </div>
  </div>
</template>

<script>
  export default {
    data() {
      let checkUsername = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('用户名不能为空'));
        }else {
          callback()
        }
      };
      let checkKey = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('密钥不能为空'));
        }else {
          callback()
        }
      };
      let validatePass = (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请输入密码'));
            } else {
              callback();
            }
      };
      let registerValidatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.loginForm.registerPassword !== '') {
            this.$refs.loginForm.validateField('registerPassword');
          }
          callback();
        }
      };
      return {
        loginForm: {
          username: '' ,
          password: '',
        },
        registerFrom: {
          registerUsername: '' ,
          registerKey: '' ,
          registerPassword: '',
        },
        loginRules: {
          password: [
            { validator: validatePass, trigger: 'blur' }
          ],
          username: [
            { validator: checkUsername, trigger: 'blur' }
          ]
        },
        registerRules: {
          registerPassword: [
            { validator: validatePass, trigger: 'blur' }
          ],
          registerKey: [
            { validator: checkKey, trigger: 'blur' }
          ],
          registerUsername: [
            { validator: checkUsername, trigger: 'blur' }
          ]
        },
        isLogin: true,
        login: false,
        register: false,
        isSaveLoginState: true
      };
    },
    methods: {
      // 登录按钮
      loginSubmit(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            this.login = true
            let res = await this.api.post('/admin/login', {
              username: this.loginForm.username,
              password: this.loginForm.password
            })
            if(res.code === 0){
                this.login = false
                // 是否保存登录状态
                if(this.isSaveLoginState) {
                  // 如果是保存到localStorage中
                  localStorage.token = res.data.token
                  localStorage.username = res.data.username
                  localStorage.id = res.data.id
                }else {
                  // 如果不是保存到sessionStroage中
                  sessionStorage.token = res.data.token
                  sessionStorage.username = res.data.username
                  sessionStorage.id = res.data.id
                }
                this.$router.replace({ path: `/admin` })
                this.$message({message: '登录成功',type: 'success'});
            }else {
                this.login = false
                this.$message({message: res.message,type: 'warning'});
            }
          } else {
            console.log('登录失败')
            return false
          }
        })
      },
      // 注册按钮
      registerSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.register = true
            this.api.post('/admin/register', {...this.registerFrom})
            .then(res => {
              if(res.code === 0){
                this.register = false
                this.isLogin = true
                this.resetForm(formName)
                this.$message({
                  message: res.message,
                  type: 'success'
                })
              }else {
                this.register = false
                this.$message({
                  message: res.message,
                  type: 'warning'
                });
              }
            })
          } else {
            return false
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
        this.register = false
        this.login = false
      },
    }
  }
</script>

<style lang="scss" scoped>
.login {
  background: url('../assets/images/bg.png') no-repeat;
  background-size: cover;
  width: 100%;
  height: 100vh;
  .window {
    width: 400px;
    height: 500px;
    border-radius: 4px;
    box-shadow: 0 0 8px rgba(0,0,0,.5);
    background: rgba($color: #ffffff, $alpha: 0.8);
  }
  .active {
    color: #EA6F5A;
    border-bottom: 2px solid #EA6F5A;
  }
  .fade-enter-active {
    transition: all .5s;
  }
  .fade-enter {
    opacity: 0;
  }
}
</style>